/*
 * Created by Federico Pisarello - SisDev Software (c) 2012 - fpisarello@sisdevsoft.com
 */

var popForm = 'horsesPop.php';
var popGridForm = 'horsesPopGrid.php';
var popItemForm = 'horsesPopItem.php';
var actionForm = 'horsesAction.php';

var joDataHorse;
var joDataItem;
var oTable;
var oTableItem;

/** Variable of tracking the IndexPK **/
var actionPK = undefined;
var action = undefined;

var actionItem = undefined;  
var actionPKItem = undefined;

function $_init()
{
	var gaiSelected;
	
	$(document).ready(function() {
    	oTable = $('#dt_horses').dataTable( {
					"bJQueryUI": true,
					"sPaginationType": "two_button",
					"bInfo": false,
					"bLengthChange": false,
					"bProcessing": true,
					"bServerSide": true,
					"sAjaxSource": actionForm + "?actionOfForm=search",
					"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
						if ( jQuery.inArray(aData[0], gaiSelected) != -1 )
						{
					        $(nRow).addClass('row_selected');
						}
						return nRow;
					},
					"aoColumns": [
					  			null,
					  			null,
					  			null,
					  			null,
					  			null
					  		]

				});
    	
    	/* Click event handler */
    	$('#dt_horses tbody tr').live('click', function () {
    		var aData = oTable.fnGetData(this);
    		var iId = aData[0];
    		actionPK = aData[0];
    		
    		gaiSelected =  [];
    		if ( $(this).hasClass('row_selected') ) {
	            $(this).removeClass('row_selected');
	            actionPK = undefined;
	        }
	        else {
	            oTable.$('tr.row_selected').removeClass('row_selected');
	            $(this).addClass('row_selected');
	            gaiSelected[gaiSelected.length++] = iId;
	        }
    	} );

	});
	
	$("#horsesDialog").dialog({
		autoOpen:false, 
		height:'auto', 
		width:600, 
		modal: true,
		resizable: false,
		closeOnEscape: false,
		position : ['center',2],		
		dialogClass:'no-close',
		beforeClose: function() { $_ClearHorsesPopForm(); },
	});
	
	$("#horsesRacingDialog").dialog({
		autoOpen:false, 
		height:'auto', 
		width:600, 
		modal: true,
		resizable: false,
		closeOnEscape: false,
		position : ['center',2],		
		dialogClass:'no-close',
		beforeClose: function() { $_ClearHorsesPopGridForm(); },
	});
	
	//Add Click for All Buttons in Search Form
	$("#btnAdd").click( function(e) {
		addProxyShow();
    });
	
	$('#btnEdit').click( function(e) {
		editProxyShow();
	});
	
	$('#btnErase').click( function(e) {
		delProxyShow();
	});
	
	$('#btnRacing').click( function(e) {
		racingProxyShow();
	});
}

function $_initPop()
{	
	var idUser;
	
	//Add Click for All Buttons in Pop Form
	$('#btnSave').click( function(e) {
		$('#horsesPopForm').submit();
	});
	$('#btnExit').click( function(e) {
		$('#horsesDialog').dialog('close');
	});
	
	$('#horseYears').numeric();
	
	//Populate Horses Data	
	if(action == iConst.EDIT)
	{
		$('#horseName').val(joDataHorse.horseName);
		$('#horseYears').val(joDataHorse.horseYears);
		$('#horseHair').val(joDataHorse.horseHair);
		$('#horsePretreatments').val(joDataHorse.horsePretreatments);
		$('#horseTemperament').val(joDataHorse.horseTemperament);
		
		idUser = joDataHorse.idUser;
	}
		
	$_ValidatorSetDefaults();
	$_initPopValidator();
	
	if($('#horseUser').length > 0)
	{
		//Populate Combos
		$.ajax({ 
		    url: actionForm, 
		    type:'POST',
		    data: 'actionOfForm=getUsers', 
		    dataType: 'json', 
		    success: function(json) { 
		    	$('#horseUser').append($('<option>').text("...").attr('value', ""));
		        $.each(json, function(i, value) {
		        	if(value.idUser == idUser)
		        		$('#horseUser').append($('<option selected>').text(value.userCompleteName).attr('value', value.idUser));
		        	else
		        		$('#horseUser').append($('<option>').text(value.userCompleteName).attr('value', value.idUser));
		        });
		    }
		});
	}
}

function $_initPopGrid()
{

	//Add Click for All Buttons in Pop Form
	$('#btnRaceExit').click( function(e) {
		$('#horsesRacingDialog').dialog('close');
	});
	$('#btnRaceAdd').click( function(e) {
		addItemRacingProxyShow();
	});
	
	$("#horseItemRacingDialog").dialog({
		autoOpen:false,
		position : ['center',2],
		height:'auto', 
		width:600, 
		modal: true,
		dialogClass:'no-close',
		beforeClose: function() {$_ClearItemHorsePopForm();}
	});
	
	oTableItem = $('#dt_racingHorse').dataTable( {
					"bJQueryUI": true,
					"sDom": 'lfrtip',
					"bInfo": false,
					"bRetrieve": true,
					"bFilter": false,
					"bPaginate": false,
					"sScrollY": "auto",
					"bLengthChange": false,
					"bSearchable":false,
					"bProcessing": true,
					"bServerSide": true,
					"bAutoWidth": true,
					"bSort": false,
					"sAjaxSource": actionForm + "?actionOfForm=searchRacing&idHorse=" + actionPK,
					"aoColumns": [
									null,
									null,
									null
								]
				});
}

function addItemRacingProxyShow()
{
	actionItem = iConst.NEW;
	actionPKItem = undefined;
	$('#horseItemRacingDialog').load(popItemForm).dialog('open');
}

function editItemRacingProxyShow(idHorseRacing)
{
	actionPKItem = idHorseRacing;
	actionItem = iConst.RACING;
	var paramData =  "actionOfForm=" + actionItem + "&idHorseRacing=" + actionPKItem;
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj)
                            {
        						joDataItem = jsonObj;
        						//Open Pop Dialog
        						$('#horseItemRacingDialog').load(popItemForm).dialog('open');
                            }
        });
}

function $_initItemPop()
{
	//Add Click for All Buttons in Pop Form
	$('#btnItemExit').click( function(e) {
		$('#horseItemRacingDialog').dialog('close');
	});
	$('#btnItemSave').click( function(e) {
		$('#horsesPopItemForm').submit();
	});
	
	$('#horseRaceDistance').numeric();
	$("#horseDateRace").mask('99/99/9999',{placeholder:" "}).datepicker({
		showOptions: { direction: "up" },
		dateFormat: 'dd/mm/yy',
		changeMonth: true,
		changeYear: true
	});
	
	if(actionItem == iConst.RACING) {
		$('#horseDateRace').val(joDataItem.horseDateRacing);
		$('#horseRaceDistance').val(joDataItem.horseDistance);
	}
	
	$_initPopItemValidator();
}

function addProxyShow()
{
	//Reset State of action and IndexPK
	actionPK = undefined;
	action = iConst.NEW;
	oTable.$('tr.row_selected').removeClass('row_selected');
	$('#horsesDialog').load(popForm).dialog('open');
}

function editProxyShow()
{
	if(actionPK === undefined)
	{
		$_showMessage('ALERT', 'ALERTA', strMenssageSelectionRecordInGrid);
		return;
	}
	
	action = iConst.EDIT;
	var paramData =  "actionOfForm=" + iConst.EDIT + "&idHorse=" + actionPK;
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj)
                            {
        						joDataHorse = jsonObj;
        						//Open Pop Dialog
        						$('#horsesDialog').load(popForm).dialog('open');
                            }
        });
	
return true;
}

function racingProxyShow()
{
	if(actionPK === undefined)
	{
		$_showMessage('ALERT', 'ALERTA', strMenssageSelectionRecordInGrid);
		return;
	}
	
	action = iConst.RACING;
	$('#horsesRacingDialog').load(popGridForm).dialog('open');
}

function $_saveItemRace(actionItem)
{
	var paramData = 'actionOfForm=addOrEditItem&' + $("#horsesPopItemForm").serialize() + "&idHorse=" + actionPK;
	
	if(actionItem == iConst.RACING)
		paramData += '&idHorseRacing=' + actionPKItem;
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj){
            if(jsonObj.status === 'OK'){
				$('#horseItemRacingDialog').dialog('close');
				oTableItem.fnReloadAjax();
			}
			else
				$_showMessage('ERR', jsonObj.status, jsonObj.msg);
        }
    });

return true;
}

function $_saveHorse(action)
{
	var paramData = 'actionOfForm=addOrEdit&' + $("#horsesPopForm").serialize();
	
	if(action == iConst.EDIT)
		paramData += '&idHorse=' + actionPK;
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj){
            if(jsonObj.status === 'OK'){
				$_showMessage('OK', jsonObj.status, jsonObj.msg);
				$('#horsesDialog').dialog('close');
				oTable.fnReloadAjax();
			}
			else
				$_showMessage('ERR', jsonObj.status, jsonObj.msg);
        }
    });

return true;
}

function delProxyShow()
{
	if(actionPK === undefined)
	{
		$_showMessage('ALERT', 'ALERTA', strMenssageSelectionRecordInGrid);
		return;
	}
	
	action = iConst.DELETE;
	
	$("#deleteHorsesDialog").dialog({
		autoOpen: false, 
		width:350,
		position: 'center',
		open: function () {
			$('#btnConfirmDelete').click( function(e) {
				$_del();
			});
			$('#btnExitDelete').click( function(e) {
				$('#deleteHorsesDialog').dialog('close')
			})
		}
	});
	$('#deleteHorsesDialog').dialog('open');	
}

function $_del()
{
	var paramData = 'actionOfForm=' + action + '&idHorse=' + actionPK;

    $.ajax({
            type: 'POST',
            url: actionForm,
            data: paramData,
			dataType: 'json',
            success: function(jsonObj)
                                {
                                    if(jsonObj.status === 'OK'){
										$_showMessage('OK', 'OK', jsonObj.msg);
										
										//Reset State of action and IndexPK
										actionPK = undefined;
										action = iConst.NEW;
										oTable.fnReloadAjax();
									}
									else
										$_showMessage('ERR', 'ERROR', jsonObj.msg);
                                    $('#deleteHorsesDialog').dialog('close');
                                }
            });

return true;
}

function deleteItemRacing(idHorseRacing)
{	
	actionItem = iConst.DELETEITEM;
	actionPKItem = idHorseRacing;
	
	$("#deleteHorsesRaceDialog").dialog({
		autoOpen: false, 
		width:350,
		position: 'center',
		open: function () {
			$('#btnConfirmDeleteItem').click( function(e) {
				$_delItem();
			});
			$('#btnExitDeleteItem').click( function(e) {
				$('#deleteHorsesRaceDialog').dialog('close')
			})
		}
	});
	$('#deleteHorsesRaceDialog').dialog('open');	
}

function $_delItem()
{
	var paramData = 'actionOfForm=' + actionItem + '&idHorseRacing=' + actionPKItem;

    $.ajax({
            type: 'POST',
            url: actionForm,
            data: paramData,
			dataType: 'json',
            success: function(jsonObj)
                                {
                                    if(jsonObj.status === 'OK'){										
										//Reset State of action and IndexPK
										actionPKItem = undefined;
										actionItem = iConst.NEW;
										oTableItem.fnReloadAjax();
									}
									else
										$_showMessage('ERR', 'ERROR', jsonObj.msg);
                                    $('#deleteHorsesRaceDialog').dialog('close');
                                }
            });

return true;
}

function $_initPopValidator()
{
	$('#horsesPopForm').validate({
		submitHandler: function() {
			$_saveHorse(action);
		}, 		
		rules: {
			horseName: {required: true,minlength: 1},
			horseYears: {required: true,minlength: 1},
			horseHair: {required: true,minlength: 1},
			horseTemperament: {required: true,minlength: 1},
			horseUser: {required: true,minlength: 1}
		},
		messages: {
			horseName: {required: '',minlength: ''},
			horseYears: {required: '',minlength: ''},
			horseHair: {required: '',minlength: ''},
			horseTemperament: {required: '',minlength: ''},
			horseUser: {required: '',minlength: ''}
		}
	});	
}

function $_initPopItemValidator()
{
	$('#horsesPopItemForm').validate({
		submitHandler: function() {
			$_saveItemRace(actionItem);
		}, 		
		rules: {
			horseDateRace: {required: true,minlength: 1},
			horseRaceDistance: {required: true,minlength: 1}
		},
		messages: {
			horseDateRace: {required: '',minlength: ''},
			horseRaceDistance: {required: '',minlength: ''}
		}
	});
}


function $_ClearHorsesPopForm()
{	
	$("#horsesDialog").empty();
}

function $_ClearHorsesPopGridForm()
{	
	$("#horsesRacingDialog").empty();
}

function $_ClearItemHorsePopForm()
{
	$("#horseItemRacingDialog").empty();
}